from pymongo import MongoClient
import json


class Json2Mongo(object):
    def __init__(self):
        self.host = '101.201.112.120'
        self.port = 27017
        # 创建mongodb客户端
        self.client = MongoClient(self.host, self.port)
        # 创建数据库dialog
        self.db = self.client.medsns
        # 创建集合scene
        self.collection = self.db.druglist

    # 写入数据库
    def write_database(self):
        file = open("/Users/syy/Desktop/druglist1.json", 'r', encoding='utf-8')
        papers = []
        for lines in file.readlines():
            dic = json.loads(lines)
            for line in dic['RECORDS']:
                del(line['_id'])
                papers.append(line)
            try:
                self.collection.insert_many(papers)
                print('写入成功')
            except Exception as e:
                print(e)
    # 从数据库读取
    def read_datebase( self ):
        try:
            myquery = {"name": "dfcg_ivr"} # 查询条件
            scene_flow = self.collection.find(myquery)
            print(type(scene_flow))
            for x in scene_flow:
                print(type(x))
                print(x)
            print ('读取成功')
        except Exception as e:
            print (e)

def stripFile(oldFName,newFName):
    '''remove the space or Tab or enter in a file,and output to a new file in the same folder'''
    fp = open(oldFName,"r+")
    newFp = open(newFName,"w")
    for eachline in fp.readlines():
        newStr = eachline.replace(" ","").replace("\t","").strip()

        newFp.write(newStr)
    fp.close()
    newFp.close()

if __name__ == '__main__':
# """
# 先处理文件再倒入
#     newName = '/Users/syy/Desktop/druglist1.json'
#     stripFile('/Users/syy/Desktop/druglist.json',newName)
# """
#     jm.read_datebase()

    jm = Json2Mongo()
    jm.write_database()
